from DataLayer import ConnDBAndCloseDB
from DataLayer import UserDataLoad
from DataLayer import CargoDataLoad
from DataLayer import OrderFormDataLoad

class CargoInfo:
    def __init__(self,carg_no,carg_desc,carg_photo,carg_price):
        self.no=carg_no                         # 1.货物编号
        self.name=carg_desc.split(";")[0]       # 2.货物名称
        self.photo=carg_photo                   # 3.图片
        self.desc=carg_desc.split(";")[1]       # 4.货物描述信息
        self.price=carg_price                   # 5.价格

    def toString(self):
        return "{} {} {} {}".format(self.name,self.photo,self.desc,self.price)

## 顾客信息加载
# 加载内容：
# 1.账号
# 2.头像
# 3.地址
# 4.余额
# 5.折扣
# 6.总花销
def customerInfoLoad(account):
    conn,cur=ConnDBAndCloseDB.connectDB()
    customer=UserDataLoad.selCustomerByAcc(cur,account)
    ConnDBAndCloseDB.closeDB(cur,conn)
    dictTemp={
        'account':account,
        'photo':customer.photo,
        'address':customer.address,
        'balance':customer.balance,
        'discount':customer.discount,
        'expend':customer.expend,
    }
    return dictTemp

## 货物信息加载，顾客
# 加载内容：
# 1.图片
# 2.描述信息
# 3.价格
def cargoInfoLoadForCus(num):
    # num代表第几页，若num=1，则返回前12件货物
    conn, cur = ConnDBAndCloseDB.connectDB()
    allCargo=CargoDataLoad.selAllNotDeleteCargo(cur)
    cargoDict = {}
    for i in range(12):
        index=(num-1)*12+i
        if(index>=len(allCargo)):
            break
        elem=CargoInfo(allCargo[index][0],allCargo[index][-2],allCargo[index][-3],allCargo[index][1])
        cargoDict[i] ={'no':elem.no,'name':elem.name,'desc':elem.desc,'photo':elem.photo,'price':elem.price}
        # print(cargoDict[i].toString())
    ConnDBAndCloseDB.closeDB(cur, conn)
    return cargoDict

# 根据订单细则生成订单
def generateOrderForm(account,orderDertail):
    # 可能产生的错误信息
    # 返回0：要求用户地址信息不完整，要求用户完善地址信息
    # 返回1：产生订单正常
    conn, cur = ConnDBAndCloseDB.connectDB()
    customer=UserDataLoad.selCustomerByAcc(cur,account)
    if customer.address=="个人地址":
        ConnDBAndCloseDB.closeDB(cur, conn)
        return 0
    else:
        # 创建一个空订单
        orderForm_no=OrderFormDataLoad.addOrderForm(conn,cur,customer)
        blankForm=OrderFormDataLoad.selOrderFormByOrfo_no(cur,orderForm_no)
        sum=0
        for i in orderDertail:
            # 数据处理：所有空格改成空字符串
            i_no=i['no'].replace(" ","")
            i_num=i['num'].replace(" ","")
            # 搜索货物
            cargo=CargoDataLoad.selCargoByCarg_no(cur,i_no)
            # print(cargo)
            # print(cargo.toString())
            # 减少储存量
            # 添加订单细则
            OrderFormDataLoad.addOrderFormDetail(conn,cur,blankForm,cargo,int(i_num))
            # 计算订单总金额
            sum+=cargo.price*int(i_num)
        # 修改订单总金额
        OrderFormDataLoad.modiOrderFormTotal(conn,cur,blankForm,sum)
        ConnDBAndCloseDB.closeDB(cur, conn)
        return 1

## 订单信息加载，顾客
# 订单信息加载，未结算0
# 订单信息加载，已结算1
# 订单信息加载，已完成2
# 订单信息加载，申请退费3
# 订单信息加载，已退费4
# 上述内容四选一
# 返回信息
# 订单号，时间，账单描述，总金额，状态
class OrderFormInfo:
    def __init__(self,no,date,desc,total,status):
        self.no=no
        self.date=date
        self.desc=desc
        self.total=total
        self.status=status

    def toString(self):
        return "{} {} {} {} {}".format(self.no,self.date,self.desc,self.total,self.status)

def orderFormLoadForCus(account,mode):
    conn, cur = ConnDBAndCloseDB.connectDB()
    customer=UserDataLoad.selCustomerByAcc(cur,account)
    FormSet=OrderFormDataLoad.selOrderFormByCus_no(cur,customer.no)
    FormDict={}
    count=0
    for i in FormSet:
        if i[-3]==mode:
            # 生成desc字符串
            desc=""
            details=OrderFormDataLoad.selOrderDetialByorfo_no(cur,i[0])
            for j in details:
                cargoName=CargoDataLoad.selCargoByCarg_no(cur,j[1]).desc.split(";")[0]
                descElem=cargoName+"*"+str(j[2])
                desc+=descElem+"；"
            elem=OrderFormInfo(i[0],i[2],desc,i[3],i[-3])
            if elem.status==0:
                statusStr='未结算'
            elif elem.status==1:
                statusStr = '已结算'
            elif elem.status==2:
                statusStr = '已完成'
            elif elem.status==3:
                statusStr = '已申请退费'
            else:
                # elem.status==4
                statusStr = '已退费'
            FormDict[count]={'no':elem.no,'date':str(elem.date),'desc':elem.desc,'total':str(elem.total),'status':statusStr}
            count+=1
    ConnDBAndCloseDB.closeDB(cur, conn)
    return FormDict

# 结算
# 余额充足，修改账单状态，账户余额扣费，结算成功返回1；余额不足返回0
def orderFormPay(account,orfo_no):
    conn, cur = ConnDBAndCloseDB.connectDB()
    customer=UserDataLoad.selCustomerByAcc(cur,account)
    orderForm=OrderFormDataLoad.selOrderFormByOrfo_no(cur,orfo_no)
    if customer.balance>=orderForm.total:
        # 把未结算改成已结算
        OrderFormDataLoad.modiOrderFormStatus(conn,cur,orderForm,1)
        # 账户余额扣费
        UserDataLoad.modiCustomerBalance(conn,cur,customer,(customer.balance-orderForm.total)*customer.discount)
        ConnDBAndCloseDB.closeDB(cur, conn)
        return 1
    else:
        ConnDBAndCloseDB.closeDB(cur, conn)
        return 0

# 获取未删除货物的总数
def getNotDeleteCargoNum():
    conn, cur = ConnDBAndCloseDB.connectDB()
    allCargo = CargoDataLoad.selAllNotDeleteCargo(cur)
    ConnDBAndCloseDB.closeDB(cur, conn)
    return len(allCargo)

# 修改密码
def modiCustomerPwd(account,oldPwd,newPwd,affirmPwd):
    conn, cur = ConnDBAndCloseDB.connectDB()
    customer=UserDataLoad.selCustomerByAccAndPwd(cur,account,oldPwd)
    if not customer:
        ConnDBAndCloseDB.closeDB(cur, conn)
        return -1        # 原密码输入错误
    else:
        if newPwd==affirmPwd:
            # 数据库修改密码
            user=UserDataLoad.selUserBasicByAccount(cur,account)
            UserDataLoad.modiUserBasicPwd(conn,cur,user,newPwd)
            ConnDBAndCloseDB.closeDB(cur, conn)
            return 1    # 正确
        else:
            ConnDBAndCloseDB.closeDB(cur, conn)
            return 0    # 新密码与确认密码不相符

# 修改基本信息
def modiCustomerBasicInfo(account,accountAlter,address):
    conn, cur = ConnDBAndCloseDB.connectDB()
    user=UserDataLoad.selUserBasicByAccount(cur,account)
    customer=UserDataLoad.selCustomerByAcc(cur,account)

    userAnother = UserDataLoad.selUserBasicByAccount(cur, accountAlter)
    if userAnother:
        # 不修改账户名
        if userAnother.account==account:
            UserDataLoad.modiCustomerAddr(conn, cur, customer, address)
            ConnDBAndCloseDB.closeDB(cur, conn)
            return 1        # 不修改账户名，只修改地址
        # 账户名与其他账户名重名
        else:
            ConnDBAndCloseDB.closeDB(cur, conn)
            return 0        # 重名
    else:
        # 修改账户名和地址
        UserDataLoad.modiCustomerAddr(conn, cur, customer, address)
        UserDataLoad.modiUserBasicAccount(conn, cur, user, accountAlter)
        ConnDBAndCloseDB.closeDB(cur, conn)
        return 2

# 修改金钱数值
def modiCustomerBalance(account,money):
    conn, cur = ConnDBAndCloseDB.connectDB()
    customer=UserDataLoad.selCustomerByAcc(cur,account)
    UserDataLoad.modiCustomerBalance(conn,cur,customer,money)
    ConnDBAndCloseDB.closeDB(cur, conn)
    return


if __name__ == '__main__':
    # cargoInfoLoadForCus(2)
    # print(getNotDeleteCargoNum())
    dict=orderFormLoadForCus('13476861589',0)
    # print(dict)
    for i in dict:
        print(dict[i])
